/**
 * 任务中心前端脚本
 */

class TaskCenter {
    constructor() {
        this.baseURL = 'http://localhost:8080';
        this.token = this.getToken();
        this.tasks = [];
        this.projects = [];
        this.users = [];
        this.currentTask = null;
        this.isEditing = false;
        this.currentFilter = 'all';
    }

    /**
     * 获取JWT令牌
     */
    getToken() {
        return localStorage.getItem('token') || sessionStorage.getItem('token');
    }

    /**
     * 通用API请求方法
     */
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.token}`,
                ...options.headers
            },
            ...options
        };

        try {
            const response = await fetch(url, config);
            
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    /**
     * 获取所有任务
     */
    async loadTasks() {
        try {
            this.showLoading();
            this.tasks = await this.request('/tasks');
            this.renderTasks();
        } catch (error) {
            this.showError('加载任务列表失败: ' + error.message);
        }
    }

    /**
     * 获取用户任务
     */
    async loadUserTasks() {
        try {
            this.showLoading();
            this.tasks = await this.request('/tasks/user');
            this.renderTasks();
        } catch (error) {
            this.showError('加载用户任务失败: ' + error.message);
        }
    }

    /**
     * 获取项目列表
     */
    async loadProjects() {
        try {
            this.projects = await this.request('/projects');
            this.renderProjectOptions();
        } catch (error) {
            console.error('加载项目列表失败:', error);
        }
    }

    /**
     * 获取用户列表
     */
    async loadUsers() {
        try {
            this.users = await this.request('/users');
            this.renderUserOptions();
        } catch (error) {
            console.error('加载用户列表失败:', error);
        }
    }

    /**
     * 创建任务
     */
    async createTask(taskData) {
        try {
            const newTask = await this.request('/tasks', {
                method: 'POST',
                body: JSON.stringify(taskData)
            });
            
            this.tasks.unshift(newTask);
            this.renderTasks();
            this.closeModal();
            this.showSuccess('任务创建成功！');
        } catch (error) {
            this.showModalError('创建任务失败: ' + error.message);
        }
    }

    /**
     * 更新任务
     */
    async updateTask(id, taskData) {
        try {
            const updatedTask = await this.request(`/tasks/${id}`, {
                method: 'PUT',
                body: JSON.stringify(taskData)
            });
            
            const index = this.tasks.findIndex(t => t.id === id);
            if (index !== -1) {
                this.tasks[index] = updatedTask;
            }
            
            this.renderTasks();
            this.closeModal();
            this.showSuccess('任务更新成功！');
        } catch (error) {
            this.showModalError('更新任务失败: ' + error.message);
        }
    }

    /**
     * 更新任务状态
     */
    async updateTaskStatus(id, status) {
        try {
            const updatedTask = await this.request(`/tasks/${id}/status`, {
                method: 'PATCH',
                body: JSON.stringify({ status })
            });
            
            const index = this.tasks.findIndex(t => t.id === id);
            if (index !== -1) {
                this.tasks[index] = updatedTask;
            }
            
            this.renderTasks();
            this.showSuccess('任务状态更新成功！');
        } catch (error) {
            this.showError('更新任务状态失败: ' + error.message);
        }
    }

    /**
     * 删除任务
     */
    async deleteTask(id) {
        if (!confirm('确定要删除这个任务吗？此操作不可撤销。')) {
            return;
        }

        try {
            await this.request(`/tasks/${id}`, {
                method: 'DELETE'
            });
            
            this.tasks = this.tasks.filter(t => t.id !== id);
            this.renderTasks();
            this.showSuccess('任务删除成功！');
        } catch (error) {
            this.showError('删除任务失败: ' + error.message);
        }
    }

    /**
     * 搜索任务
     */
    async searchTasks() {
        const keyword = document.getElementById('searchInput').value.trim();
        const statusFilter = document.getElementById('statusFilter').value;
        const priorityFilter = document.getElementById('priorityFilter').value;
        
        try {
            let tasks;
            if (keyword) {
                tasks = await this.request(`/tasks/search?keyword=${encodeURIComponent(keyword)}`);
            } else {
                tasks = await this.request('/tasks');
            }
            
            // 应用筛选条件
            if (statusFilter) {
                tasks = tasks.filter(task => task.status === statusFilter);
            }
            if (priorityFilter) {
                tasks = tasks.filter(task => task.priority === priorityFilter);
            }
            
            this.tasks = tasks;
            this.renderTasks();
        } catch (error) {
            this.showError('搜索任务失败: ' + error.message);
        }
    }

    /**
     * 筛选任务
     */
    async filterTasks(filterType) {
        this.currentFilter = filterType;
        
        // 更新筛选标签样式
        document.querySelectorAll('.filter-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        event.target.classList.add('active');
        
        try {
            let tasks;
            switch (filterType) {
                case 'all':
                    tasks = await this.request('/tasks');
                    break;
                case 'my':
                    tasks = await this.request('/tasks/user');
                    break;
                case 'urgent':
                    tasks = await this.request('/tasks');
                    tasks = tasks.filter(task => task.priority === 'URGENT');
                    break;
                case 'overdue':
                    tasks = await this.request('/tasks');
                    const today = new Date().toISOString().split('T')[0];
                    tasks = tasks.filter(task => 
                        task.dueDate && task.dueDate < today && 
                        task.status !== 'COMPLETED' && task.status !== 'CANCELLED'
                    );
                    break;
                default:
                    tasks = await this.request('/tasks');
            }
            
            this.tasks = tasks;
            this.renderTasks();
        } catch (error) {
            this.showError('筛选任务失败: ' + error.message);
        }
    }

    /**
     * 渲染任务列表
     */
    renderTasks() {
        const container = document.getElementById('tasksContainer');
        
        if (this.tasks.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <h3>暂无任务</h3>
                    <p>点击"新建任务"按钮创建第一个任务</p>
                </div>
            `;
            return;
        }

        const tasksHTML = this.tasks.map(task => this.renderTaskCard(task)).join('');
        container.innerHTML = `<div class="tasks-grid">${tasksHTML}</div>`;
    }

    /**
     * 渲染单个任务卡片
     */
    renderTaskCard(task) {
        const priorityClass = this.getPriorityClass(task.priority);
        const statusClass = this.getStatusClass(task.status);
        const isOverdue = task.dueDate && new Date(task.dueDate) < new Date() && 
                         task.status !== 'COMPLETED' && task.status !== 'CANCELLED';
        
        return `
            <div class="task-card ${isOverdue ? 'overdue' : ''}">
                <div class="task-header">
                    <h3 class="task-title">${task.taskName || '未命名任务'}</h3>
                    <span class="task-priority ${priorityClass}">
                        ${this.getPriorityText(task.priority)}
                    </span>
                </div>
                
                <div class="task-meta">
                    <div class="task-meta-item">
                        <span>📁</span>
                        <span>${task.projectName || '未分配项目'}</span>
                    </div>
                    <div class="task-meta-item">
                        <span>👤</span>
                        <span>${task.assigneeName || '未分配'}</span>
                    </div>
                    <div class="task-meta-item">
                        <span>📅</span>
                        <span>${task.dueDate || '无截止日期'}</span>
                        ${isOverdue ? '<span style="color: #dc3545; font-weight: bold;">（已逾期）</span>' : ''}
                    </div>
                </div>
                
                ${task.description ? `<div class="task-description">${task.description}</div>` : ''}
                
                <div class="task-status ${statusClass}">
                    ${this.getStatusText(task.status)}
                </div>
                
                <div class="task-actions">
                    <button class="btn btn-primary btn-sm" onclick="taskCenter.viewTask(${task.id})">
                        👁️ 查看
                    </button>
                    <button class="btn btn-warning btn-sm" onclick="taskCenter.editTask(${task.id})">
                        ✏️ 编辑
                    </button>
                    <select class="btn btn-sm" onchange="taskCenter.quickUpdateStatus(${task.id}, this.value)" style="padding: 4px 8px;">
                        <option value="">状态</option>
                        <option value="TODO" ${task.status === 'TODO' ? 'selected' : ''}>待开始</option>
                        <option value="IN_PROGRESS" ${task.status === 'IN_PROGRESS' ? 'selected' : ''}>进行中</option>
                        <option value="COMPLETED" ${task.status === 'COMPLETED' ? 'selected' : ''}>已完成</option>
                        <option value="CANCELLED" ${task.status === 'CANCELLED' ? 'selected' : ''}>已取消</option>
                    </select>
                    <button class="btn btn-danger btn-sm" onclick="taskCenter.deleteTask(${task.id})">
                        🗑️ 删除
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * 快速更新任务状态
     */
    async quickUpdateStatus(taskId, newStatus) {
        if (!newStatus) return;

        await this.updateTaskStatus(taskId, newStatus);
    }

    /**
     * 渲染项目选项
     */
    renderProjectOptions() {
        const select = document.getElementById('projectId');
        select.innerHTML = '<option value="">请选择项目</option>' +
            this.projects.map(project => `
                <option value="${project.id}">${project.projectName}</option>
            `).join('');
    }

    /**
     * 渲染用户选项
     */
    renderUserOptions() {
        const select = document.getElementById('assigneeId');
        select.innerHTML = '<option value="">请选择负责人</option>' +
            this.users.map(user => `
                <option value="${user.id}">${user.fullName || user.username}</option>
            `).join('');
    }

    /**
     * 获取优先级样式类
     */
    getPriorityClass(priority) {
        const priorityMap = {
            'URGENT': 'priority-urgent',
            'HIGH': 'priority-high',
            'MEDIUM': 'priority-medium',
            'LOW': 'priority-low'
        };
        return priorityMap[priority] || 'priority-medium';
    }

    /**
     * 获取优先级显示文本
     */
    getPriorityText(priority) {
        const priorityMap = {
            'URGENT': '紧急',
            'HIGH': '高',
            'MEDIUM': '中',
            'LOW': '低'
        };
        return priorityMap[priority] || priority;
    }

    /**
     * 获取状态样式类
     */
    getStatusClass(status) {
        const statusMap = {
            'TODO': 'status-todo',
            'IN_PROGRESS': 'status-in-progress',
            'COMPLETED': 'status-completed',
            'CANCELLED': 'status-cancelled'
        };
        return statusMap[status] || 'status-todo';
    }

    /**
     * 获取状态显示文本
     */
    getStatusText(status) {
        const statusMap = {
            'TODO': '待开始',
            'IN_PROGRESS': '进行中',
            'COMPLETED': '已完成',
            'CANCELLED': '已取消'
        };
        return statusMap[status] || status;
    }

    /**
     * 显示创建任务模态框
     */
    showCreateModal() {
        this.isEditing = false;
        this.currentTask = null;

        document.getElementById('modalTitle').textContent = '新建任务';
        document.getElementById('taskForm').reset();
        document.getElementById('modalError').style.display = 'none';

        // 设置默认截止日期为明天
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        document.getElementById('dueDate').value = tomorrow.toISOString().split('T')[0];

        // 加载项目和用户列表
        this.loadProjects();
        this.loadUsers();

        document.getElementById('taskModal').style.display = 'block';
    }

    /**
     * 查看任务详情
     */
    async viewTask(id) {
        try {
            const task = await this.request(`/tasks/${id}`);
            this.showTaskDetails(task, true); // 只读模式
        } catch (error) {
            this.showError('获取任务详情失败: ' + error.message);
        }
    }

    /**
     * 编辑任务
     */
    async editTask(id) {
        try {
            const task = await this.request(`/tasks/${id}`);
            this.showTaskDetails(task, false); // 编辑模式
        } catch (error) {
            this.showError('获取任务详情失败: ' + error.message);
        }
    }

    /**
     * 显示任务详情
     */
    showTaskDetails(task, readOnly = false) {
        this.isEditing = !readOnly;
        this.currentTask = task;

        document.getElementById('modalTitle').textContent = readOnly ? '任务详情' : '编辑任务';
        document.getElementById('modalError').style.display = 'none';

        // 填充表单数据
        document.getElementById('taskName').value = task.taskName || '';
        document.getElementById('description').value = task.description || '';
        document.getElementById('dueDate').value = task.dueDate || '';
        document.getElementById('priority').value = task.priority || 'MEDIUM';
        document.getElementById('status').value = task.status || 'TODO';

        // 加载项目和用户列表并设置当前值
        Promise.all([this.loadProjects(), this.loadUsers()]).then(() => {
            document.getElementById('projectId').value = task.projectId || '';
            document.getElementById('assigneeId').value = task.assigneeId || '';
        });

        // 设置表单只读状态
        const formElements = document.querySelectorAll('#taskForm input, #taskForm select, #taskForm textarea');
        formElements.forEach(element => {
            element.disabled = readOnly;
        });

        // 更新保存按钮
        const saveButton = document.querySelector('.modal-footer .btn-success');
        if (readOnly) {
            saveButton.style.display = 'none';
        } else {
            saveButton.style.display = 'inline-block';
            saveButton.textContent = '更新';
        }

        document.getElementById('taskModal').style.display = 'block';
    }

    /**
     * 保存任务
     */
    async saveTask() {
        const form = document.getElementById('taskForm');
        const formData = new FormData(form);

        const taskData = {
            taskName: formData.get('taskName'),
            description: formData.get('description'),
            projectId: parseInt(formData.get('projectId')),
            assigneeId: parseInt(formData.get('assigneeId')),
            priority: formData.get('priority'),
            status: formData.get('status'),
            dueDate: formData.get('dueDate') || null
        };

        // 验证必填字段
        if (!taskData.taskName || !taskData.projectId || !taskData.assigneeId ||
            !taskData.priority || !taskData.status || !taskData.dueDate) {
            this.showModalError('请填写所有必填字段');
            return;
        }

        if (this.isEditing && this.currentTask) {
            await this.updateTask(this.currentTask.id, taskData);
        } else {
            await this.createTask(taskData);
        }
    }

    /**
     * 关闭模态框
     */
    closeModal() {
        document.getElementById('taskModal').style.display = 'none';
        document.getElementById('taskForm').reset();
        document.getElementById('modalError').style.display = 'none';

        // 恢复表单可编辑状态
        const formElements = document.querySelectorAll('#taskForm input, #taskForm select, #taskForm textarea');
        formElements.forEach(element => {
            element.disabled = false;
        });

        // 恢复保存按钮
        const saveButton = document.querySelector('.modal-footer .btn-success');
        saveButton.style.display = 'inline-block';
        saveButton.textContent = '保存';
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const container = document.getElementById('tasksContainer');
        container.innerHTML = '<div class="loading">加载中...</div>';
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        const container = document.getElementById('tasksContainer');
        container.innerHTML = `<div class="error">❌ ${message}</div>`;
    }

    /**
     * 显示模态框错误信息
     */
    showModalError(message) {
        const errorDiv = document.getElementById('modalError');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }

    /**
     * 显示成功信息
     */
    showSuccess(message) {
        // 创建临时成功提示
        const successDiv = document.createElement('div');
        successDiv.className = 'success';
        successDiv.textContent = '✅ ' + message;
        successDiv.style.position = 'fixed';
        successDiv.style.top = '20px';
        successDiv.style.right = '20px';
        successDiv.style.zIndex = '9999';
        successDiv.style.padding = '15px 20px';
        successDiv.style.borderRadius = '4px';
        successDiv.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';

        document.body.appendChild(successDiv);

        setTimeout(() => {
            document.body.removeChild(successDiv);
        }, 3000);
    }

    /**
     * 初始化
     */
    init() {
        // 检查登录状态
        if (!this.token) {
            alert('请先登录');
            window.location.href = '/login.html';
            return;
        }

        // 加载任务列表
        this.loadTasks();

        // 绑定搜索框回车事件
        document.getElementById('searchInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.searchTasks();
            }
        });

        // 绑定模态框点击外部关闭事件
        document.getElementById('taskModal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('taskModal')) {
                this.closeModal();
            }
        });
    }
}

// 全局函数
function showCreateModal() {
    taskCenter.showCreateModal();
}

function closeModal() {
    taskCenter.closeModal();
}

function saveTask() {
    taskCenter.saveTask();
}

function loadTasks() {
    taskCenter.loadTasks();
}

function searchTasks() {
    taskCenter.searchTasks();
}

function filterTasks(filterType) {
    taskCenter.filterTasks(filterType);
}

// 创建全局实例
const taskCenter = new TaskCenter();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    taskCenter.init();
});
